<script setup>
import { reactive, ref } from "vue";
import { User, Lock } from "@element-plus/icons-vue";
import request from "../utils/request";
import { ElMessage } from "element-plus";
import { useUserStore } from "../stores/user.js";
import router from "../router/index.js";

// 双向绑定的数据，可获取输入框的数据
const loginData = reactive({});

// 账号和密码的输入规则，配合prop属性使用才有效
const rules = reactive({
  username: [{ required: true, message: "请输入账号", trigger: "blur" }],
  password: [
    { required: true, message: "请输入密码", trigger: "blur" },
    { min: 6, max: 8, message: "长度为6-8", trigger: "blur" },
  ],
});

// 表单校验，登陆时传递给后台前的校验，看看是否输入账号和密码
const ruleFormRef = ref();
function login() {
  ruleFormRef.value.validate((valid) => {
    if (valid) {
      //    校验成功
      request.post("/login", loginData).then((res) => {
        if (res.code === "200") {
          ElMessage.success("登陆成功");
          // 登陆成功后将登录的用户数据保存
          const userStore = useUserStore();
          userStore.setUser(res.data);
          userStore.setToken(res.token);
          if(res.data.identity === "a"){
            router.push("/adminHome/admin_booklist")
          }else{
            router.push("/home1/booklist");
          }
          
        } else {
          ElMessage.error(res.msg);
        }
      });
    } else {
      // 校验失败
      ElMessage.error("请输入合法数据");
    }
  });
}

const register = () => {
  router.push("/register");
};
</script>

<template>
  <div>
    <div class="login">
      <el-form
        ref="ruleFormRef"
        :model="loginData"
        status-icon
        :rules="rules"
        size="large"
      >
        <div
          style="
            text-align: center;
            color: dodgerblue;
            font-size: 25px;
            font-weight: bold;
            margin-bottom: 25px;
          "
        >
          登录
        </div>
        <el-form-item prop="username">
          <el-input
            v-model="loginData.username"
            placeholder="请输入账号"
            :prefix-icon="User"
          />
        </el-form-item>
        <el-form-item prop="password">
          <el-input
            v-model="loginData.password"
            type="password"
            placeholder="请输入密码"
            :prefix-icon="Lock"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" style="width: 100%" @click="login"
            >登录</el-button
          >
        </el-form-item>
        <el-link @click="register">还没有账号？请注册账号</el-link>
      </el-form>
    </div>
  </div>
</template>

<style scoped>
.login {
  position: absolute;
  width: 400px;
  height: 300px;
  background-color: beige;
  right: 150px;
  top: 220px;
  padding: 10px;
}
</style>